package com.no1.musicmgr.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.no1.musicmgr.entity.Music;
import com.no1.musicmgr.entity.User;
import com.no1.musicmgr.service.MusicService;
import com.no1.musicmgr.service.UserService;
import com.no1.musicmgr.util.CodeUtil;
import com.no1.musicmgr.util.DateUtil;
import com.no1.musicmgr.util.ImgCodeUtil;
import com.no1.musicmgr.util.UUIDUtil;
import com.no1.musicmgr.vo.Imgcode;
import com.no1.musicmgr.vo.PageQueryBean;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Pattern;

import static com.no1.musicmgr.util.CodeUtil.*;

@Tag(name = "UserController", description = "用户管理模块")
@Log4j
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private MusicService musicService;

    @Operation(summary = "用户注册")
    @PostMapping("/user")
    @Parameter(name = "user", description = "用户对象，封装用户名和密码+身份")
    public boolean doAdd(User user) {
        user.setUser_id(UUIDUtil.getUUID());
        if (user.getUser_sf() == null || user.getUser_sf() == 0) {
            user.setUser_sf(1);    // 注册默认用户身份为 1
        }
        if (user.getUser_sjh() == null || user.getUser_sjh().isEmpty()) {
            user.setUser_sjh("101010101234");
        }
        if (user.getUser_email() == null || user.getUser_email().isEmpty()) {
            user.setUser_email("00123@123.com");
        }
        return userService.register(user);
    }

    @Operation(summary = "用户登录")
    @GetMapping("/user")
    public User doLogin(@Parameter(description = "用户对象，封装用户名和密码") User user) {
        String username = user.getUser_name();
        if(username.contains("@")){
            user.setUser_email(username);
            user.setUser_name("");
        }
        if(Pattern.matches("^\\d{11}$", username))
        {
            user.setUser_sjh(username);
            user.setUser_name("");

        }
        log.info("登录的user:" + user);
        return userService.select(user);
    }

    @Operation(summary = "常规验证码")
    @GetMapping("/user/yzm1")
    public String getCode01(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String code = CodeUtil.getCode01(4);
        String fileName = "yzm_" + CodeUtil.codeImgFile() + ".png";
        String outputPath = "c:/static/directory/" + fileName;

        ImgCodeUtil.convertStringToImage(code, outputPath);
        CodeUtil.saveCodeToRedis("code_key", String.valueOf(code));
        log.info("常规验证码: " + code);
        return fileName;
    }

    @Operation(summary = "校验常规验证码")
    @GetMapping("/user/yzm1/{codeImg01}")
    @Parameter(name = "codeImg01", description = "常规验证码")
    public boolean selectCodeImg01(@PathVariable("codeImg01") String codeImg01) {
        boolean rel = CodeUtil.getCodeFromRedis("code_key").equals(codeImg01);
        log.info("常规验证码校验结果: " + rel);
        return rel;
    }


    @Operation(summary = "计算验证码")
    @GetMapping("/user/yzm2")
    public String getCode02(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Imgcode imgcode = CodeUtil.getCode02(20);
        String text = imgcode.getCode();
        Integer res = imgcode.getRes();
        CodeUtil.saveCodeToRedis("code_key", String.valueOf(res));
        String fileName = "yzm_" + CodeUtil.codeImgFile() + ".png";
        String outputPath = "c:/static/directory/" + fileName;
        ImgCodeUtil.convertStringToImage(text, outputPath);
        log.info("计算验证码: " + text);
        return fileName;
    }

    @Operation(summary = "检验运算验证码")
    @GetMapping("/user/yzm2/{codeImg02}")
    @Parameter(name = "codeImg02", description = "运算验证码")
    public boolean selectCodeImg02(@PathVariable("codeImg02") int codeImg02) {
        int res = Integer.parseInt(CodeUtil.getCodeFromRedis("code_key"));
        return res == codeImg02;
    }

    @Operation(summary = "用户列表")
    @GetMapping("/user/list")
    @Parameter(name = "user", description = "用户对象，获取用户列表")
    @Parameter(name = "page", description = "分页对象")
    @Parameter(name = "request", description = "请求对象")
    @Parameter(name = "response", description = "响应对象")
    protected PageInfo<User> doList(User user, PageQueryBean page, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 分页设置
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        // 查询
        log.info("查询的user:" + user);
        // 格式的转化
        String createDate = user.getCreateDate();
        log.info("查询的createDate:" + user.getCreateDate());
        if (createDate != null && !createDate.equals("")) {
            if (createDate.length() == 4) {
                if (Integer.parseInt(createDate) < 1232) {
                    user.setCreateDate(DateUtil.formatDate(createDate));
                }
            } else {
                user.setCreateDate(DateUtil.formatDate(createDate));
            }
        }
        log.info("设置后的createDate:" + user.getCreateDate());
        String loginDate = user.getLoginDate();
        log.info("查询的loginDate:" + user.getLoginDate());
        if (loginDate != null && !loginDate.equals("")) {
            if (loginDate.contains(":")) {
                String[] timeParts = loginDate.split(":");
                user.setLoginHour(timeParts[0]);
                user.setLoginMinute(timeParts[1]);
                user.setLoginSecond(timeParts[2]);
            } else {
                if (loginDate.length() == 4) {
                    if (Integer.parseInt(loginDate) < 1232) {
                        user.setLoginDate(DateUtil.formatDate(loginDate));
                    }
                } else {
                    user.setLoginDate(DateUtil.formatDate(loginDate));
                }
            }
        }


        log.info("设置后的loginDate:" + user.getLoginDate());
        log.info("设置后的user："+user);
        ArrayList<User> list = userService.list(user);
        log.info("查询结果：" + list);
        return new PageInfo<User>(list);
    }

    private void formatConversion(User user, String loginDate) {
        if (loginDate != null && !loginDate.isEmpty()) {
            if (loginDate.length() == 4) {
                if (Integer.parseInt(loginDate) < 1232) {
                    user.setCreateDate(DateUtil.formatDate(loginDate));
                }
            } else {
                user.setCreateDate(DateUtil.formatDate(loginDate));
            }
        }
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/user/{id}")
    @Parameter(name = "id", description = "用户id")
    public boolean deleteById(@PathVariable("id") String id) {
        return userService.deleteById(id);
    }


    @Operation(summary = "查询用户")
    @GetMapping("/user/{username}")
    @Parameter(name = "yhm", description = "用户名")
    public boolean selectYhm(@PathVariable("username") String yhm) {
        return userService.isYhmUnique(yhm);
    }


    @Operation(summary = "修改用户名")
    @PutMapping("/user/yhmupdate")

    public boolean updateYhm(User user) {
        return userService.updateYhm(user);
    }


    @Operation(summary = "修改密码")
    @PutMapping("/user/pwdupdate")

    public boolean updatePwd(User user) {
//        System.out.println("user:"+user);
        return userService.updatePwd(user);
    }

    //查询新用户
    @Operation(summary = "用户列表和歌曲")
    @GetMapping("/user/list1")
    @Parameter(name = "user", description = "用户对象，获取用户列表")
    @Parameter(name = "page", description = "分页对象")
    @Parameter(name = "request", description = "请求对象")
    @Parameter(name = "response", description = "响应对象")
    protected PageInfo<User> doList1(User user, Music music, PageQueryBean page) {
        // 分页设置
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        // 查询
        log.info("查询的user:" + user);
        log.info("设置后的loginDate:" + user.getLoginDate());
        ArrayList<User> list = userService.list(user);
        return new PageInfo<User>(list);
    }

    @Operation(summary = "查询用户")
    @PutMapping("/user/upupdate")
    @Parameter(name = "user", description = "用户")
    public boolean selectme(User user) {
        System.out.println("user:"+user);
        return userService.update(user);
    }

    @Operation(summary = "根据用户ID查询")
    @GetMapping("/users")
    @Parameter(name = "user_id", description = "用户id")
    public User selectById(String user_id) {
        User user = new User();
        user.setUser_id(user_id);
        return userService.selectById(user);
    }
    @Operation(summary = "根据用户ID查询")
    @GetMapping("/user/selectUser/{user_id}")
    @Parameter(name = "user_id", description = "用户id")
    public User select1ById(@PathVariable("user_id") String user_id) {
        log.info("user_id:" + user_id);
        User user = userService.selectme(user_id);
        ArrayList<Music> list = musicService.myMusic(user_id);
        user.setMusic_sc(list.size());
        Music music = new Music();
        music.setMusic_user_id(user_id);
        ArrayList<Music> list1=musicService.list1Music(music);
        user.setMusic_sl(list1.size());
        log.info("user:" + user);
        return user;
    }
}


